package v1

import (
	"easyVolunteer/middleware"
	"easyVolunteer/model"
	"easyVolunteer/utils/errno"
	"easyVolunteer/utils/validate"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

func Login(c *gin.Context) {
	var u model.UserLogin
	err1 := c.ShouldBindJSON(&u)
	if err1 != nil {
		log.Println("参数解析失败")
		c.JSON(http.StatusOK, gin.H{
			"code": errno.ErrParseParameter.Code,
			"msg":  errno.ErrParseParameter.Message,
		})
		return
	}

	// 数据验证
	tips, err := validate.Validate(&u)
	if err != errno.OK {
		c.JSON(http.StatusOK, gin.H{
			"code":   err.Code,
			"msg":    err.Message,
			"detail": tips,
		})
		return
	}
	// 判断密码
	//body, _ := ioutil.ReadAll(c.Request.Body)
	//c.String(http.StatusOK, string(body))

	code, role := model.Login(u.UserID, u.PassWord)
	token, status := setToken(u.UserID)
	if status != errno.OK {
		c.JSON(http.StatusOK, gin.H{
			"code": errno.ErrTokenSetUpFail.Code,
			"msg":  errno.ErrTokenSetUpFail.Message,
		})
		return
	}
	if code == errno.OK {
		c.JSON(http.StatusOK, gin.H{
			"code":  errno.OK.Code,
			"role":  role,
			"token": token,
			"msg":   errno.OK.Message,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code.Code,
		"msg":  code.Message,
	})
}

func setToken(userID string) (string, *errno.Errno) {
	j := middleware.NewJWT()
	claims := middleware.MyClaims{
		UserID: userID,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 100,
			ExpiresAt: time.Now().Unix() + 60000,
			Issuer:    "mixinju",
		},
	}

	token, err := j.CreateToken(claims)
	if err != nil {
		return "", errno.ErrTokenSetUpFail
	}

	return token, errno.OK
}
